/**
 * 
 */
package com.csc.bankingsystem.core.service.impl;

import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.csc.bankingsystem.core.dao.TokenRecordDAO;
import com.csc.bankingsystem.core.dao.UserInfoDAO;
import com.csc.bankingsystem.core.entity.TokenRecord;
import com.csc.bankingsystem.core.entity.UserInfo;
import com.csc.bankingsystem.core.service.TokenRecordService;
import com.csc.bankingsystem.core.util.EncryptionUtil;


/**
 * Implement all service operation of TokenRecordService
 * @author angelkid
 *
 */
@Service("tokenRecordService")
@Transactional
public class TokenRecordServiceImpl implements TokenRecordService {
	@Autowired
	TokenRecordDAO tokenRecordDAO;
	
	@Autowired
	UserInfoDAO userInfoDAO;

	public TokenRecord find(long id) {
		return tokenRecordDAO.find(id);
	}

	public List<TokenRecord> findAll() {
		return tokenRecordDAO.findAll();
	}

	public Long countAll() {
		return tokenRecordDAO.countAll();
	}

	public Long save(TokenRecord tokenRecord){
		return tokenRecordDAO.save(tokenRecord);
	}

	public void update(TokenRecord tokenRecord){
		tokenRecordDAO.update(tokenRecord);
	}

	public void delete(TokenRecord tokenRecord) {
		tokenRecordDAO.delete(tokenRecord);
	}
	
	public TokenRecord findFirstByTokenAndUserInfoId(String tokenMD5, long id){
		return tokenRecordDAO.findFirstByTokenAndUserInfoId(tokenMD5,id);
	}
	
	public String createTokenForLoginId(String loginId) throws NoSuchAlgorithmException{
		if(loginId == null){
			throw new IllegalArgumentException("loginId is null");
		}
		Date now = new Date();
		UserInfo userInfo= userInfoDAO.getUserInfoByLoginId(loginId);
		List<TokenRecord> listTokenRecord = tokenRecordDAO.findByUserInfoId(userInfo.getId());
		if(!CollectionUtils.isEmpty(listTokenRecord)){
			tokenRecordDAO.delete(listTokenRecord);
		}
		
		String randomStr = UUID.randomUUID().toString();
		String tokenMD5 = EncryptionUtil.generateMD5HashFromString(randomStr + loginId);
		TokenRecord tokenRecord = new TokenRecord();
		tokenRecord.setCreateDate(now);
		tokenRecord.setCreateUser(loginId);
		tokenRecord.setUserInfo(userInfo);
		tokenRecord.setTokenMD5(tokenMD5);
		
		tokenRecordDAO.save(tokenRecord);
		return randomStr;
	}

	public void deleteTokenForLoginId(UserInfo userInfo) {
		List<TokenRecord> listTokenRecord = tokenRecordDAO.findByUserInfoId(userInfo.getId());
		if(!CollectionUtils.isEmpty(listTokenRecord)){
			tokenRecordDAO.delete(listTokenRecord);
		}
	}
	
	
}

